import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';

import '../../../../common/values/images.dart';
import '../../../../common/models/index.dart';
import '../controller.dart';

/// 🎯 活动卡片组件
/// 
/// 用于在首页展示单个活动信息，支持：
/// - 多图横向滑动浏览
/// - 圆点指示器显示当前图片位置
/// - 用户信息展示
/// - 活动详情展示（支持展开/收起）
/// - 操作按钮（关闭、联系、加入）
class ActivityCard extends StatefulWidget {
  final ActivityEntity activity;
  final int index;
  final HomeIndexController controller;

  const ActivityCard({
    Key? key,
    required this.activity,
    required this.index,
    required this.controller,
  }) : super(key: key);

  @override
  State<ActivityCard> createState() => _ActivityCardState();
}

class _ActivityCardState extends State<ActivityCard> {
  // 🔥 活动详情展开/收起状态
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 🖼️ 背景图片轮播
        _buildImageSwiper(),
        
        // 🎨 渐变遮罩 - 不接收指针事件，让手势传递到下层图片
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: IgnorePointer(
            child: _buildGradientMask(),
          ),
        ),
        
        // 📝 底部信息区域 - 只有按钮区域可点击，其他区域不拦截手势
        _buildBottomInfo(),
      ],
    );
  }

  /// 🖼️ 构建图片轮播
  Widget _buildImageSwiper() {
    final images = widget.activity.activityImages ?? [];
    
    if (images.isEmpty) {
      // 没有图片时显示占位图
      return Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Color(0xFF6B73FF), Color(0xFF9068BE)],
          ),
        ),
        child: const Center(
          child: Icon(
            Icons.image_not_supported_outlined,
            size: 80,
            color: Colors.white54,
          ),
        ),
      );
    }
    
    if (images.length == 1) {
      // 单张图片
      return CachedNetworkImage(
        imageUrl: images[0],
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        // 🔥 移除固定缓存尺寸，保持图片原始比例，避免拉伸
        fadeInDuration: Duration.zero,
        fadeOutDuration: Duration.zero,
        placeholder: (context, url) => Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFF1a1a1a), Color(0xFF000000)],
            ),
          ),
        ),
        errorWidget: (context, url, error) => Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFF1a1a1a), Color(0xFF000000)],
            ),
          ),
          child: const Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.error_outline, color: Colors.white54, size: 48),
                SizedBox(height: 12),
                Text(
                  '图片加载失败',
                  style: TextStyle(color: Colors.white54, fontSize: 14),
                ),
              ],
            ),
          ),
        ),
      );
    }
    
    // 🔥 多张图片轮播 - 使用专门的轮播组件
    return _ImageSwiperWidget(
      images: images,
      controller: widget.controller,
    );
  }

  /// 🎨 渐变遮罩（只返回Container，Positioned在外层）
  Widget _buildGradientMask() {
    return Container(
      height: MediaQuery.of(Get.context!).size.height * 0.6,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.transparent,
            Colors.black.withOpacity(0.8),
          ],
        ),
      ),
    );
  }

  /// 📝 构建底部信息区域
  Widget _buildBottomInfo() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: IgnorePointer(
        ignoring: false, // 整体不忽略，只是内部特定元素忽略
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 👤 用户信息 - 不接收指针事件，让手势传递到图片
                IgnorePointer(
                  child: _buildUserInfo(),
                ),
                
                const SizedBox(height: 12),
                
                // 📍 活动标题 - 不接收指针事件
                IgnorePointer(
                  child: Text(
                    widget.activity.activityTitle,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                
                // 📝 活动详情 - 支持展开/收起
                if (widget.activity.activityDetails != null && widget.activity.activityDetails!.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  _buildExpandableDetails(),
                ],
                
                const SizedBox(height: 20),
                
                // 🎯 操作按钮 - 保持可点击
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 📝 构建可展开/收起的活动详情
  Widget _buildExpandableDetails() {
    return LayoutBuilder(
      builder: (context, constraints) {
        // 创建TextSpan用于测量文本
        final textSpan = TextSpan(
          text: widget.activity.activityDetails!,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 14,
            height: 1.4,
          ),
        );
        
        final textPainter = TextPainter(
          text: textSpan,
          maxLines: 2,
          textDirection: TextDirection.ltr,
        );
        
        textPainter.layout(maxWidth: constraints.maxWidth);
        
        // 判断文本是否超过2行
        final isTextOverflow = textPainter.didExceedMaxLines;
        
        // 如果文本不超过2行，直接显示全部内容
        if (!isTextOverflow) {
          return Text(
            widget.activity.activityDetails!,
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 14,
              height: 1.4,
            ),
          );
        }
        
        // 文本超过2行，显示展开/收起功能
        return GestureDetector(
          onTap: () {
            setState(() {
              _isExpanded = !_isExpanded;
            });
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 文本内容
              Stack(
                children: [
                  // 主文本
                  Text(
                    widget.activity.activityDetails!,
                    style: const TextStyle(
                      color: Colors.white70,
                      fontSize: 14,
                      height: 1.4,
                    ),
                    maxLines: _isExpanded ? null : 2,
                    overflow: _isExpanded ? TextOverflow.visible : TextOverflow.fade,
                  ),
                  // 未展开时，在右下角显示展开按钮
                  if (!_isExpanded)
                    Positioned(
                      bottom: 0,
                      right: 0,
                      child: Container(
                        padding: const EdgeInsets.only(left: 16),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              Colors.black.withOpacity(0.0),
                              Colors.black.withOpacity(0.3),
                            ],
                          ),
                        ),
                        child: Text(
                          ' 展开',
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.95),
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            shadows: [
                              Shadow(
                                color: Colors.black.withOpacity(0.5),
                                blurRadius: 2,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              // 如果已展开，显示收起按钮
              if (_isExpanded) ...[
                const SizedBox(height: 6),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                          color: Colors.white.withOpacity(0.2),
                          width: 0.5,
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            '收起',
                            style: TextStyle(
                              color: Colors.white.withOpacity(0.95),
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(width: 2),
                          Icon(
                            Icons.keyboard_arrow_up,
                            color: Colors.white.withOpacity(0.95),
                            size: 16,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  /// 👤 构建用户信息
  Widget _buildUserInfo() {
    return Row(
      children: [
        // 用户名
        Text(
          widget.activity.publisherNickname ?? '未知用户',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        
        const SizedBox(width: 8),
        
        // 性别标签
        Container(
          width: 20,
          height: 20,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              colors: widget.activity.publisherGender == '女'
                  ? [const Color(0xFFFF6B9D), const Color(0xFFC94B84)]
                  : [const Color(0xFF4FC3F7), const Color(0xFF29B6F6)],
            ),
          ),
          child: Center(
            child: Text(
              widget.activity.genderIcon,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
              ),
            ),
          ),
        ),
        
        const Spacer(),
        
        // 距离
        Row(
          children: [
            Image.asset(
              AssetsImages.locationPng,
              width: 14,
              height: 14,
              color: Colors.white70,
            ),
            const SizedBox(width: 4),
            Text(
              '距离${widget.activity.distanceText}',
              style: const TextStyle(
                color: Colors.white70,
                fontSize: 13,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 🎯 构建操作按钮（根据好友关系动态显示）
  Widget _buildActionButtons() {
    // 🔥 获取发布者关系类型（传入当前活动的索引，确保检查的是正确的活动）
    final relationType = widget.controller.getPublisherRelationType(
      activityIndex: widget.index,
    );
    
    return Row(
      children: [
        // ✕ 关闭按钮
        Container(
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.black.withOpacity(0.3),  // 🎨 半透明黑色背景
            border: Border.all(
              color: Colors.white.withOpacity(0.2),  // 🎨 白色半透明边框
              width: 0.5,
            ),
          ),
          child: IconButton(
            onPressed: widget.controller.onCloseActivity,
            icon: const Icon(
              Icons.close,
              color: Colors.white,
              size: 24,
            ),
          ),
        ),
        
        const SizedBox(width: 12),
        
        // 🔥 中间按钮：根据关系类型动态显示
        Expanded(
          child: _buildMiddleButton(relationType),
        ),
        
        const SizedBox(width: 12),
        
        // ➕ 加入按钮（图标+文字）
        Container(
          height: 50,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3),  // 🎨 半透明黑色背景
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
              color: Colors.white.withOpacity(0.2),  // 🎨 白色半透明边框
              width: 0.5,
            ),
          ),
          child: TextButton.icon(
            onPressed: widget.controller.onJoinActivity,
            style: TextButton.styleFrom(
              padding: EdgeInsets.zero,
              minimumSize: Size.zero,
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
            icon: const Icon(
              Icons.add_circle_outline,
              color: Colors.white,
              size: 20,
            ),
            label: const Text(
              '加入',
              style: TextStyle(
                color: Colors.white,
                fontSize: 15,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }
  
  /// 🎨 构建中间按钮（根据关系类型）
  Widget _buildMiddleButton(String relationType) {
    switch (relationType) {
      case 'mine':
        // 🎨 我的活动 - 蓝色半透明
        return Container(
          height: 50,
          decoration: BoxDecoration(
            color: Colors.blue.withOpacity(0.3),  // 🎨 蓝色半透明背景
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
              color: Colors.white.withOpacity(0.2),
              width: 0.5,
            ),
          ),
          child: TextButton(
            onPressed: null,  // 我的活动不可点击
            child: const Text(
              '我的活动',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
        
      case 'friend':
        // 💬 联系我 - 黑色半透明（好友）
        return Container(
          height: 50,
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3),  // 🎨 黑色半透明背景
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
              color: Colors.white.withOpacity(0.2),
              width: 0.5,
            ),
          ),
          child: TextButton(
            onPressed: widget.controller.onContactTap,
            child: const Text(
              '联系我',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
        
      case 'stranger':
      default:
        // 👥 加好友 - 红色半透明（陌生人）
        return Container(
          height: 50,
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.3),  // 🎨 红色半透明背景
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
              color: Colors.white.withOpacity(0.2),
              width: 0.5,
            ),
          ),
          child: TextButton(
            onPressed: widget.controller.onAddFriendTap,
            child: const Text(
              '加好友',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
    }
  }
}

/// 🖼️ 多图轮播组件 - 学习playtrue3的实现
class _ImageSwiperWidget extends StatefulWidget {
  final List<String> images;
  final HomeIndexController controller;
  
  const _ImageSwiperWidget({
    required this.images,
    required this.controller,
  });
  
  @override
  State<_ImageSwiperWidget> createState() => _ImageSwiperWidgetState();
}

class _ImageSwiperWidgetState extends State<_ImageSwiperWidget> {
  late PageController _pageController;
  
  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }
  
  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    // 🔥 学习playtrue3：直接使用PageView，不使用NotificationListener
    // Flutter的手势系统会自动处理横向和纵向滑动的区别
    // 🎨 图片指示器已移至AppBar右侧，不再需要圆点指示器
    return PageView.builder(
      controller: _pageController,
      onPageChanged: (index) {
        // 🔥 通知controller更新AppBar的图片指示器
        widget.controller.updateImageIndex(index);
      },
      itemCount: widget.images.length,
      itemBuilder: (context, imageIndex) {
        return CachedNetworkImage(
          imageUrl: widget.images[imageIndex],
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
          // 🔥 移除固定缓存尺寸，保持图片原始比例，避免拉伸
          fadeInDuration: Duration.zero,
          fadeOutDuration: Duration.zero,
          placeholder: (context, url) => Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFF1a1a1a), Color(0xFF000000)],
              ),
            ),
          ),
          errorWidget: (context, url, error) => Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFF1a1a1a), Color(0xFF000000)],
              ),
            ),
            child: const Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.error_outline, color: Colors.white54, size: 48),
                  SizedBox(height: 12),
                  Text(
                    '图片加载失败',
                    style: TextStyle(color: Colors.white54, fontSize: 14),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

